home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3190 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  60 lines

  1. Path: newsfeed.internetmci.com!iol!usenet
  2. From: "John D. Hourihane" <hourihaj@iol.ie>
  3. Newsgroups: comp.lang.c
  4. Subject: Can a function return a (pointer to a) function?
  5. Date: 26 Jan 1996 19:33:30 GMT
  6. Organization: Ireland On-Line
  7. Message-ID: <4ebaaa$jh6@barnacle.iol.ie>
  8. NNTP-Posting-Host: dialup-158.dublin.iol.ie
  9.  
  10. Hello world,
  11.  
  12. I am trying to write a function which will return a pointer to a function,
  13. but I'm having no luck.
  14.  
  15. The toy program below illustrates (I hope) what I want to be able to do,
  16. but as it stands it won't compile for me. The idea is that the call to
  17. '(pick(ADD))' will return a pointer to the 'add' function which is then
  18. dereferenced and used.
  19.  
  20. But like I say, it doesn't compile. It complains 'Declaration terminated
  21. incorrectly' as I declare 'pick'. I'm using Turbo C/C++.
  22.  
  23. Any reply, posted here or by email, would be great.
  24.  
  25. PHiL
  26.  
  27. /* The toy program, to use a function that returns a
  28.  * pointer to a function.
  29.  */
  30.  
  31. #include <stdio.h>
  32.  
  33. #define ADD            0
  34. #define MULTIPLY    1
  35.  
  36. int add(int x, int y);
  37. int multiply(int x, int y);
  38.  
  39. /* pick returns a pointer to a function which will operate on two integers */
  40. (int f(int, int)) *pick(int s);
  41.  
  42. int main()
  43. {
  44.     printf("5 + 4 = %d\n", (*(pick(ADD)))(5,4));
  45.     printf("5 * 4 = %d\n", (*(pick(MULTIPLY)))(5,4));
  46.     return 0;
  47. }
  48.  
  49. int add(int x, int y)
  50. {    return x + y; }
  51.  
  52. int multiply(int x, int y)
  53. {    return x * y; }
  54.  
  55. (int f(int, int)) *pick(int s)
  56. {    if (s == ADD)
  57.         return add;
  58.     return multiply;
  59. }
  60.